import argparse
import os
import sys
import logging

from django.utils import simplejson as json
from django.core.exceptions import ObjectDoesNotExist

from ippool.models import Host

logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)


parser = argparse.ArgumentParser(description='ip pool db writer')
parser.add_argument('ipdump', help='File containing ip and port entries in jsonline format.')
parser.add_argument('--verbose', '-v', action='count', help='Be verbose about actions performed (-v info, -vv - debug)')
args = parser.parse_args()

fp = open(args.ipdump)
ln = 1
for ip_ln in fp.readlines():
	try:
		ip = json.loads(ip_ln)
		if args.verbose > 0:
			logging.debug('Processing %s...' % ip)
		try:
			host = Host.objects.get(ipaddress = ip['ipaddress'], port = ip['port'])
			host.is_alive = True
			host.save()
			if args.verbose > 0:
				logging.debug('%s already in db, resurrected...' % ip)
		except ObjectDoesNotExist:
			host = Host(ipaddress = ip['ipaddress'], port = ip['port'])
			host.save()
			if args.verbose > 0:
				logging.debug('Added %s to db.' % ip)
		ln += 1
	except Exception, e:
		logging.error('Failed to process %s (line: %d), reason: %s' % (ip_ln, ln, e))
fp.close()
